#!/usr/bin/env perl
#
# A
# EM4102 decoded: 0D 00 3B 07 A7
# EM4102        : FF 83 60 01  
#                 AE 07 D1 FE
# Byte track    : FF 7F C1 B0
#                 00 D7 03 E8
# B
# EM4102 decoded: 10 00 50 98 CA
# EM4102        : FF 8C 00 02
#                 81 28 E2 86
# Byte track    : FF 8C 00 02
#                 81 28 E2 86
#

use strict;
use warnings;

my @bytesAo = ( 0xFF,
               0x7F,
               0xC1,
               0x01,
               0x00,
               0xD7, 
               0x03, 
               0xE8 );

my @bytesA = ( 0xFF,
               0x83,
               0x60,
               0x01,
               0xAE,
               0x07, 
               0xD1, 
               0xFE );

my @bytesB = ( 0xFF,  # 0 header 9 ones (0x1F or 0xFF8x, filled out?)
               0x8C,  # 1 h00,d00,d01,d02, d03,PP0,d10,d11    0,1,2,3, 4,5,6,7
               0x00,  # 2 d12,d13,PP1,d20, d21,d22,d23,PP2    8,9,a,b, c,d,e,f
               0x02,  # 3 d30,d31,d32,d33, PP3,d40,d41,d42   10,1,2,3, 4,5,6,7
               0x81,  # 4 d43,PP4,d50,d51, d52,d53,PP5,d60   18,9,a,b, c,d,e,f
               0x20,  # 5 d61,d62,d63,PP6, d70,d71,d72,d73   20,1,2,3, 4,5,6,7
               0xE2,  # 6 PP7,d80,d81,d82, d83,PP8,d90,d91   28,9,a,b, c,d,e,f
               0x86   # 7 d92,d93,PP9                        30,1,2,3
               );

my @bytes;
#@bytes = @bytesA;
@bytes = map { ~$_ } @bytesAo;

printf("bytes[1]: %2X \n", $bytes[1]);

#  brute fucking force from EM4102.pdf
my $d0 = ($bytes[1] & 0b01111000) >> 3;
my $d1 = ($bytes[1] & 0b00000011) << 2 | ($bytes[2] & 0b11000000) >> 6;
my $d2 = ($bytes[2] & 0b00011110) >> 1;
my $d3 = ($bytes[3] & 0b11110000) >> 4;
my $d4 = ($bytes[3] & 0b00000111) << 1 | ($bytes[4] & 0b10000000) >> 7;
my $d5 = ($bytes[4] & 0b00111100) >> 2;
my $d6 = ($bytes[4] & 0b00000001) << 3 | ($bytes[5] & 0b11100000) >> 5;
my $d7 = ($bytes[5] & 0b00001111);
my $d8 = ($bytes[6] & 0b01111000) >> 3;
my $d9 = ($bytes[6] & 0b00000011) << 2 | ($bytes[7] & 0b11000000) >> 6;
printf("d01: %X%X\n", $d0,$d1);
printf("d23: %X%X\n", $d2,$d3);
printf("d45: %X%X\n", $d4,$d5);
printf("d67: %X%X\n", $d6,$d7);
printf("d89: %X%X\n", $d8,$d9);

#my $bits = pack("b*", '0'x64);
#my $o=0;
#for(my $i=1; $i<8; $i++) {
#    printf "byte %d (%02X) at offset %d\n", $i,$bytes[$i],$o;
#    vec($bits,$o,8) = $bytes[$i];
#    $o+=8;
#}
#
#my $bitz = unpack("b*", $bits);
#print "bitz:$bitz\n";
#
#for(my $i=0; $i<10; $i++) {
#    $o = 1+($i*5);
#    my $d = vec($bits, $o, 4);
#    printf("%X (%X), ", $d,$o);
#}
#print("\n");

#my $b64 = pack("Q1", @bytes);
#for(my $i=0; $i<10; $i++) {
#    $o = 1+($i*5);
#    my $d = ($b64 & (0x0f<<$o)) >> $o;
#    printf("%X ",$d);
#}
#print("\n");

